package com.onlineMIS.ORM.DAO.headQ.inventory;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.onlineMIS.ORM.DAO.headQ.SQLServer.ClientDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.custMgmt.HeadQCustDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.finance.ChainAcctFlowDaoImpl;
import com.onlineMIS.ORM.entity.headQ.SQLServer.ClientsMS;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.ClientsMSVO;
import com.onlineMIS.ORM.entity.headQ.custMgmt.HeadQCust;
import com.onlineMIS.common.Common_util;

@Service
public class BasicInforService {
	/**
	 * client information in SQL server
	 */
	@Autowired
	private ClientDAOImpl clientImpl;
	
	@Autowired
	private HeadQCustDaoImpl headQCustDaoImpl;
	
	@Autowired
	private ChainAcctFlowDaoImpl chainAcctFlowDaoImpl;
	
	/**
	 * to load clients information from db
	 * as the sql server allow the 0 foreign key this is a problem in creent system
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public List<ClientsMSVO> getClientsByNameLike(String name) throws IllegalAccessException, InvocationTargetException{
		DetachedCriteria criteria = DetachedCriteria.forClass(ClientsMS.class,"client");
		criteria.add(Restrictions.like("client.name", name,MatchMode.ANYWHERE));
		criteria.add(Restrictions.eq("client.deleted", false));
		List<ClientsMS> clients = clientImpl.getClientsByCriteria(criteria);
		
		List<ClientsMSVO> cvList = new ArrayList<ClientsMSVO>();
		if (clients.size() != 0) {
			for (ClientsMS cMs : clients) {
				ClientsMSVO cMsvo  = new ClientsMSVO();
				
				HeadQCust cust = headQCustDaoImpl.get(cMs.getClient_id(), true);
				
				//1. Get the current finance期初欠款
				double initialAcct = 0.0d;
				if (cust != null) {
					initialAcct = cust.getInitialAcctBalance();
				}
								
			    //2.当前欠款
				double currentFinance = initialAcct + chainAcctFlowDaoImpl.getAcctFlowByCustId(cMs.getClient_id());
				currentFinance = Common_util.roundDouble(currentFinance, 2);
				cMsvo.setCurrentFinance(currentFinance);
				BeanUtils.copyProperties(cMsvo,cMs);
				cvList.add(cMsvo);
			}
		}
		
		return cvList;
		
	}

	/**
	 * get the client information by id
	 * @param clientId
	 * @return
	 */
	public ClientsMS getClientById(int clientId) {
		return clientImpl.get(clientId, true);
	}
	

	/**
	 * 获取所有的精算账户信息
	 * @param clientId
	 * @return
	 */
	public List<ClientsMS> getClientAll() {
		return clientImpl.getAll(true);
	}
}
